package com.android.simplelauncher;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends Activity {
    public String TAG = getClass().getName();
    Context mContext = null;
    List<HashMap<String, Object>> installApp = new ArrayList<>();
    RecyclerView recyclerView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        int color = Color.parseColor("#000000");
        setStatusBar(color);
        setContentView(R.layout.activity_main);

        mContext = this;

        getInstalledApp(this);
        recyclerView = findViewById(R.id.app_list);
        try {
            Drawable drawable = BitmapDrawable.createFromStream(getAssets().open("background.jpg"), "background");
            recyclerView.setBackground(drawable);
        } catch (Exception e) {
            e.printStackTrace();
        }
        recyclerView.setAdapter(new MyRecAdapter(mContext, R.layout.icon_icon, installApp, new ClickCallBack()));

        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
//        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);


        for (HashMap<String, Object> v : installApp) {
            if (v.get("appName") != null) {
                Log.d(TAG, "onCreate: " + v.get("appName"));
                Log.d(TAG, "onCreate: " + v.get("appIcon"));
                Log.d(TAG, "onCreate: " + v.get("appIcon1"));
                Log.d(TAG, "onCreate: " + v.get("appIcon2"));
//                Log.d(TAG, "onCreate: " + v.get("appIcon3"));

            }
        }
    }


    protected void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(color);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (color == Color.WHITE) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    private void getInstalledApp(Context activity) {
        installApp.clear();
        PackageManager packageManager = activity.getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        int count = 0;
        for (PackageInfo p : packages) {

            if ((p.applicationInfo.flags & p.applicationInfo.FLAG_SYSTEM) <= 0) {
                HashMap<String, Object> app = new HashMap<>();
                if (p.packageName != null && p.packageName != null) {
                    app.put("appIcon", p.applicationInfo.loadIcon(packageManager));
                    app.put("appIcon1", p.applicationInfo.loadBanner(packageManager));
                    app.put("appIcon2", p.applicationInfo.loadLogo(packageManager));
//                app.put("appIcon3",p.applicationInfo.loadUnbadgedIcon(packageManager));
                    app.put("appName", p.applicationInfo.loadLabel(packageManager));
                    app.put("packageName", p.packageName);
                    app.put("versionName", p.versionName);
                    count++;
                }
                installApp.add(app);
            }

        }
    }

    public void openPackage(String packageName) {

        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(pi.packageName);
            List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
            ResolveInfo ri = apps.iterator().next();

            if (ri != null) {
                String package_name = ri.activityInfo.packageName;
                String class_name = ri.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND);
                ComponentName cn = new ComponentName(package_name, class_name);
                intent.setComponent(cn);
                mContext.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ClickCallBack {
        public void hasClick(int click) {

        }

        public void hasClick(String packageName) {
            openPackage(packageName);
        }
    }

    private static class MyRecAdapter extends RecyclerView.Adapter<MyRecAdapter.AppViewHolder> {
        int layout_id = 0;
        Context nContext = null;
        List<HashMap<String, Object>> appList = null;
        ClickCallBack sListener = null;

        public MyRecAdapter(Context c, int id, List<HashMap<String, Object>> ls, ClickCallBack listener) {
            appList = ls;
            nContext = c;
            layout_id = id;
            sListener = listener;
        }

        @NonNull
        @NotNull
        @Override
        public AppViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup viewGroup, int i) {
            View v = LayoutInflater.from(nContext).inflate(layout_id, viewGroup, false);
            return new AppViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull @NotNull MainActivity.MyRecAdapter.AppViewHolder appViewHolder, int i) {
//            Glide.with(appViewHolder.appIcon).asDrawable().into(appViewHolder.appIcon);
            HashMap<String, Object> app_info = appList.get(i);

            Log.d("TAG", "onBindViewHolder: " + app_info.get("appName"));
            appViewHolder.appIcon.setImageDrawable((Drawable) app_info.get("appIcon"));
            appViewHolder.appName.setText(String.valueOf(app_info.get("appName")));
            appViewHolder.appPackage.setText(String.valueOf(app_info.get("packageName")));
            appViewHolder.appVersion.setText(String.valueOf(app_info.get("versionName")));

            appViewHolder.appLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sListener.hasClick(String.valueOf(app_info.get("packageName")));
                }
            });
        }

        @Override
        public int getItemCount() {
            return appList == null ? 0 : appList.size();
        }

        public static class AppViewHolder extends RecyclerView.ViewHolder {
            ImageView appIcon = null;
            TextView appName = null;
            TextView appVersion = null;
            TextView appPackage = null;

            LinearLayout appLayout = null;

            public AppViewHolder(@NonNull View itemView) {
                super(itemView);
                appLayout = itemView.findViewById(R.id.icon_layout);
                appIcon = itemView.findViewById(R.id.appIcon);
                appName = itemView.findViewById(R.id.appName);
                appVersion = itemView.findViewById(R.id.appVersion);
                appPackage = itemView.findViewById(R.id.appPackage);
            }
        }
    }
}